package com.common;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerGroup;
import org.csource.fastdfs.TrackerServer;

public class FastDFSUtil {

    private StorageClient1 storageClient;

    public FastDFSUtil(String config) {
        if (config.contains("classpath:")) {
            config = config.replace("classpath:", this.getClass().getResource("/").getPath());
        }
        try {
            ClientGlobal.init(config);
            TrackerGroup trackerGroup = ClientGlobal.getG_tracker_group();
            TrackerClient trackerClient = new TrackerClient(trackerGroup);
            TrackerServer trackerServer = trackerClient.getConnection();
            if (null == trackerServer) {
                throw new RuntimeException("TrackerServer can not be null.");
            }
            StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
            if (null == storageServer) {
                throw new RuntimeException("StorageServer can not be null.");
            }
            storageClient = new StorageClient1(trackerServer, storageServer);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String uploadFile(byte[] fileBytes) throws Exception {
        return uploadFile(fileBytes, null, null);
    }

    public String uploadFile(byte[] fileBytes, String ext) throws Exception {
        return uploadFile(fileBytes, ext, null);
    }

    public String uploadFile(byte[] fileBytes, String ext, NameValuePair[] metas) throws Exception {
        return storageClient.upload_file1(fileBytes, ext, metas);
    }

    public String uploadFile(String fileAbsolutelyPath) throws Exception {
        return uploadFile(fileAbsolutelyPath, null, null);
    }

    public String uploadFile(String fileAbsolutelyPath, String ext) throws Exception {
        return uploadFile(fileAbsolutelyPath, ext, null);
    }

    public String uploadFile(String fileAbsolutelyPath, String ext, NameValuePair[] metas) throws Exception {
        return storageClient.upload_file1(fileAbsolutelyPath, ext, metas);
    }

    public int deleteFile(String fileId) throws Exception {
        return storageClient.delete_file1(fileId);
    }
}